package cn.nexd.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.nexd.app.NexdApplication;
import cn.nexd.app.activity.inter.ISearchActivityView;
import cn.nexd.app.adapter.CityAdapter;
import cn.nexd.app.arsenal.R;
import cn.nexd.app.model.ExpandableModel;
import cn.nexd.app.model.MallModel;
import cn.nexd.app.presenter.ISearchPresenterImpl;
import cn.nexd.app.presenter.inter.IMallPresenter;
import cn.nexd.app.widget.MySearchView;

public class SearchActivity extends BaseActivity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, ISearchActivityView {

    private Toolbar tlSearchActivity;
    private MySearchView svMallInfo;
    private List<ExpandableModel> cityMallModels = new ArrayList<ExpandableModel>();
    private List<ExpandableModel> searchResults = new ArrayList<ExpandableModel>();
    private List<String> cities = new ArrayList<String>();
    private List<MallModel> mallInfo = new ArrayList<MallModel>();
    private List<String> mallNames = new ArrayList<String>();
    private CityAdapter cityAdapter;
    private ArrayAdapter<String> mallAdapter;
    private SwipeRefreshLayout swLayout;
    private ListView lvCities;
    private ListView lvMalls;
    private TextView tvCancle;
    private int selectedPosition = 0;
    private InputMethodManager inputSoftManager;
    private IMallPresenter iMallPresenter;
    private TextView textView;
    private boolean isSearch;
    private ActionBar actionBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MobclickAgent.openActivityDurationTrack(false);
        initToolbar();
        initView();
        initData();
        bindData();
        bindListener();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search;
    }


    private void bindListener() {
        lvMalls.setOnItemClickListener(this);
        lvCities.setOnItemClickListener(this);
        lvMalls.setOnScrollListener(this);
        lvCities.setOnScrollListener(this);
        svMallInfo.setOnQueryTextListener(this);

    }

    private void bindData() {
        cityAdapter = new CityAdapter(this, cities);
        mallAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mallNames);
        lvCities.setAdapter(cityAdapter);
        lvMalls.setAdapter(mallAdapter);
    }

    private void initData() {
        if (cityMallModels != null && cityMallModels.size() != 0) {
            cityMallModels.clear();
        }
        if (searchResults != null && searchResults.size() != 0) {
            searchResults.clear();
        }
        cities.clear();
        mallNames.clear();
        cityMallModels.addAll(NexdApplication.malls);
        searchResults.addAll(NexdApplication.malls);
        for (ExpandableModel cityMallModel : searchResults) {
            cities.add(cityMallModel.getCityName());
        }
        for (MallModel mallInfo : searchResults.get(0).getMallModels()) {
            mallNames.add(mallInfo.getMallName());
        }
    }

    private void initToolbar() {
        tlSearchActivity = (Toolbar) findViewById(R.id.search_toolbar);
        if (getSupportActionBar() != null) {
            actionBar = getSupportActionBar();
            setSupportActionBar(tlSearchActivity);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
        }

    }

    private void initView() {
        iMallPresenter = new ISearchPresenterImpl(this, this);
        svMallInfo = (MySearchView) findViewById(R.id.search_sv_mall);
        if (svMallInfo != null) {
            svMallInfo.setSearchActivity(this);
        }
        tvCancle = (TextView) findViewById(R.id.search_tv_cancel);
        if (tvCancle != null) {
            tvCancle.setOnClickListener(this);
        }
        svMallInfo.setSubmitButtonEnabled(true);
        svMallInfo.setFocusable(false);
        inputSoftManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        lvCities = (ListView) findViewById(R.id.main_lv_address);
        lvMalls = (ListView) findViewById(R.id.main_lv_mall_name);
        swLayout = (SwipeRefreshLayout) findViewById(R.id.search_addr_swipe);
        if (swLayout != null) {
            swLayout.setDistanceToTriggerSync(200);
            swLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                    android.R.color.holo_green_light,
                    android.R.color.holo_orange_light,
                    android.R.color.holo_red_light);
            swLayout.setOnRefreshListener(this);
        }
        lvCities.setSelection(0);
        removeSearchBackground();
    }


    //去掉搜索框默认背景色和设置文本位置
    private void removeSearchBackground() {
        int id = svMallInfo.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        textView = (TextView) svMallInfo.findViewById(id);
        if (svMallInfo != null) {
            try {
                Class<?> argClass = svMallInfo.getClass();
                Field ownField = argClass.getDeclaredField("mSearchPlate");
                ownField.setAccessible(true);
                View mView = (View) ownField.get(svMallInfo);
                mView.setBackgroundColor(Color.TRANSPARENT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.main_lv_address) {
            mallNames.clear();
            cityAdapter.setSelectedPosition(position);
            selectedPosition = position;
            mallInfo = searchResults.get(position).getMallModels();
            for (MallModel mallName : mallInfo) {
                mallNames.add(mallName.getMallName());
            }
            mallAdapter.notifyDataSetChanged();
            cityAdapter.notifyDataSetChanged();
        } else if (parent.getId() == R.id.main_lv_mall_name) {
            NexdApplication.selectedMallModel = searchResults.get(selectedPosition).getMallModels().get(position);
            startActivity(new Intent(SearchActivity.this, MainActivity.class));
            finish();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (firstVisibleItem == 0) {
            swLayout.setEnabled(true);
        } else {
            swLayout.setEnabled(false);
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    if (v != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        if (textView != null) {
                            textView.clearFocus();
                        }

                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) ? true : onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v == textView)) {
            if (TextUtils.isEmpty(textView.getText().toString())) {
                isSearch = false;
            }
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom ? false : true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MallListFragment"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(SearchActivity.this);
        inputSoftManager.hideSoftInputFromWindow(svMallInfo.getWindowToken(), 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (svMallInfo.isFocused()) {
                svMallInfo.setFocusable(false);
            }
            Log.d("Hello", "onBackPressed");
            this.finish();
        }
        return false;
    }

    public void queryMallInfo(String query) {
        cities.clear();
        mallNames.clear();
        searchResults.clear();
        for (ExpandableModel expandableModel : cityMallModels) {
            ArrayList<MallModel> searchModel = new ArrayList<MallModel>();
            ArrayList<MallModel> mallModels = expandableModel.getMallModels();
            String preCityName = "";
            for (int i = 0; i < mallModels.size(); i++) {
                MallModel mallModel = mallModels.get(i);
                if ((mallModel.getCnCityName() + mallModel.getMallName()).contains(query)) {
                    mallNames.add(mallModel.getMallName());
                    searchModel.add(mallModel);
                    if (!mallModel.getCnCityName().equals(preCityName)) {
                        cities.add(mallModel.getCnCityName());
                        cityAdapter.setSelectedPosition(cities.indexOf(mallModel.getCnCityName()));
                        preCityName = mallModel.getCnCityName();
                    }
                }
            }
            if (searchModel.size() != 0) {
                searchResults.add(new ExpandableModel(expandableModel.getCityName(), searchModel));
            }
        }
        if (searchResults.size() == 0) {
            showToast("您所查询的商场或城市不存在~");
        }
    }


    @Override
    public boolean onQueryTextSubmit(String query) {
        isSearch = true;
        if (textView.hasFocus()) {
            inputSoftManager.hideSoftInputFromInputMethod(svMallInfo.getWindowToken(), 0);
            svMallInfo.clearFocus();
        }
        if (TextUtils.isEmpty(query)) {
            showToast("您输入的内容为空~");
        } else {
            queryMallInfo(query);
            cityAdapter.notifyDataSetChanged();
            mallAdapter.notifyDataSetChanged();
        }
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    @Override
    public void onRefresh() {
        iMallPresenter.updateMallInfo();

    }

    @Override
    public void refreshComplete() {
        swLayout.setRefreshing(false);
        initData();
        if (!TextUtils.isEmpty(textView.getText().toString())) {
            queryMallInfo(textView.getText().toString());
        }
        if (searchResults.size() == 0) {
            return;
        }
        mallNames.clear();
        cityAdapter.setSelectedPosition(selectedPosition);
        mallInfo = searchResults.get(selectedPosition).getMallModels();
        for (MallModel mallName : mallInfo) {
            mallNames.add(mallName.getMallName());
        }
        if (cityAdapter != null && mallAdapter != null) {
            cityAdapter.notifyDataSetChanged();
            mallAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void showToast(String msg) {
        Toast.makeText(SearchActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void enterActivity() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_tv_cancel:
                finish();
                break;
        }
    }


    @Override
    public boolean onClose() {
        isSearch = false;
        return false;
    }
}
